package finelProject.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import com.google.gson.Gson;

import finelProject.MyAppConstants;
import finelProject.model.Messages;

/**
 * Servlet implementation class PostNewMessage
 */
public class PostNewMessage extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final int INITIALVALUE = 0;
	private static final double DOUBLEINITVAL = 0.0;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PostNewMessage() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Context context;
		Messages currentMessage = null;
		try {
			context = new InitialContext();
			BasicDataSource ds = (BasicDataSource)context.lookup(MyAppConstants.DB_DATASOURCE);
			Connection conn = ds.getConnection();
			
			//get the data from the request
			String Author = (String) request.getSession().getAttribute("Username");
			String Topic 		= request.getParameter("Topic");
			String Content 		= request.getParameter("Content");
			Date date = new Date();
			Timestamp TimeOfPublish = new Timestamp(date.getTime());
			int NumberOfAutorFollowers=0;
			
			PreparedStatement stmt;
			try{
				stmt = conn.prepareStatement(MyAppConstants.SUM_NUMBER_OF_FOLLOWERS);
				stmt.setString	 (1, Author);
				ResultSet rs = stmt.executeQuery();
				if(rs.next()){
					NumberOfAutorFollowers = rs.getInt(1);
				}
				
			}catch(SQLException e){
				getServletContext().log("Error while querying for customers", e);
	    		response.sendError(500);//internal server error
			}
			
			currentMessage = new Messages(Author, INITIALVALUE, TimeOfPublish, Content, Topic,NumberOfAutorFollowers);
			//insert the massage into the MESSAGES table in the DB
			
			try{
				stmt = conn.prepareStatement(MyAppConstants.PUBLISH_MESSAGE);
				
				stmt.setString	 (1, currentMessage.getTopic());
				stmt.setString	 (2, currentMessage.getAutor());
				stmt.setInt	  	 (3, currentMessage.getRepublishNumber());
				stmt.setTimestamp(4, currentMessage.getTimeOfPublish());
				stmt.setString	 (5, currentMessage.getContant());
				stmt.setInt 	 (6, currentMessage.getMessageId());
				stmt.setInt		 (7, currentMessage.getAutorNumberOfFollowers());
				stmt.setDouble	 (8, DOUBLEINITVAL);
				stmt.setString	 (9, currentMessage.parseContent(currentMessage.getContant(), getServletContext(), response));
				
				stmt.executeUpdate();
				
				//commit update
				conn.commit();
				//close statements
				stmt.close();
				
			}catch(SQLException e){
				getServletContext().log("Error while INSERT to MESSAGE", e);
				response.sendError(500);//internal server error
			}

			conn.close();
			
			Gson gson = new Gson();
			
			String MessageJsonResult = gson.toJson(currentMessage, MyAppConstants.MESSAGE);
			PrintWriter writer = response.getWriter();
	    	writer.println(MessageJsonResult);
	    	writer.close();
	    	context.close();
			
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
